package com.yjd.comm.util;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.alibaba.fastjson.JSON;
import com.yjd.comm.app.model.PushRecordModel;
import com.yjd.comm.app.service.IPushRecordService;
import com.yjd.comm.app.service.IPushRegidService;
import com.yjd.comm.system.model.SysParamModel;
import com.yjd.comm.system.util.SysParamUtil;
import com.yjd.comm.vo.Constant;
import org.apache.log4j.Logger;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 极光推送工具类
 * Created by yangchangyan on 2017/7/3.
 *
 * @param
 * @return
 * @throws
 */
public class JpushUtil {
    private static final Logger logger = Logger.getLogger(JpushUtil.class);

    private static JPushClient jPushClient;

    private static IPushRecordService pushRecordService;

    /**
     * 将需要推送的内容推送到对应的android/ios设备，默认推送平台是：android_ios
     * 推送content到regids
     *
     * @param user_id 用户id
     * @return
     * @throws
     */
    public static void pushMessage(Long user_id, Constant.SysParamKeyEnum tpl, Object ...arguments) throws Exception {
        List<Long> user_ids = new ArrayList<>();
        user_ids.add(user_id);
        pushMessage(user_ids, tpl, arguments);
    }

    /**
     * 将需要推送的内容推送到对应的android/ios设备，默认推送平台是：android_ios
     * 推送content到regids
     *
     * @param user_ids 用户id
     * @param tpl 需要推送的内容模板
     * @param arguments 模板参数
     * @return
     * @throws
     */
    public static void pushMessage(List<Long> user_ids, Constant.SysParamKeyEnum tpl, Object ...arguments) throws Exception {
        SysParamModel sysParam = SysParamUtil.getSysParamModel(tpl);
        pushMessage(user_ids, MessageFormat.format(sysParam.getParam_value(), arguments), Platform.android_ios());
    }

    /**
     * 将需要推送的内容推送到对应的android/ios设备
     * 推送content到regids
     *
     * @param user_ids 用户id
     * @param content 需要推送的内容
     * @param platform 需要推送到的平台（默认推送android_ios）
     * @return
     * @throws
     */
    public static void pushMessage(final List<Long> user_ids, final String content, final Platform platform) throws Exception {

        ThreadPoolUtil.submitTask(new Runnable() {
            @Override
            public void run() {
                try {
                    Map<String, String> param = FrameUtil.newHashMap();
                    param.put("starttime", FrameUtil.getTime().toString());

                    List<String> regids = queryRegids(user_ids);
                    if(regids.size() == 0){
                        // 推送id为空则直接返回空对象，不继续推送
                        return;
                    }

                    PushPayload load = PushPayload.newBuilder()
                            .setAudience(Audience.registrationId(regids))
                            .setPlatform(platform)
                            .setNotification(
                                    Notification.newBuilder()
                                            .setAlert(content)
                                            .addPlatformNotification(
                                                    AndroidNotification.newBuilder()
                                                            .setAlert(content)
                                                            .addExtras(param)
                                                            .build())
                                            .addPlatformNotification(
                                                    IosNotification.newBuilder()
                                                            .setAlert(content)
                                                            .addExtras(param)
                                                            .build())
                                            .build()
                            )
                            .setMessage(Message.newBuilder().addExtras(param).setMsgContent(content).build())
                            .build();

                    PushResult result = getClinent().sendPush(load);

                    // 记录推送的所有消息
                    IPushRecordService pushRecordService = getPushRecordService();
                    PushRecordModel record = null;
                    Long currentTime = FrameUtil.getTime();
                    for(Long user_id : user_ids){
                        record = new PushRecordModel();
                        record.setUser_id(user_id);
                        record.setContext(content);
                        record.setStatus(1);
                        record.setReaded(0);
                        record.setMessage(result.toString());
                        record.setCreate_time(currentTime);
                        record.setUpdate_time(currentTime);
                        pushRecordService.insert(record);
                    }
                } catch (Exception e){
                    logger.error("push message error with message:", e);
                }
            }
        });
    }

    private static List<String> queryRegids(List<Long> user_ids){
        List<String> regids = Collections.EMPTY_LIST;
        if(null == user_ids || user_ids.size() == 0){
            return regids;
        }

        IPushRegidService pushRegidService = ServiceHolder.getLocalService(IPushRegidService.class, "pushRegidService");
        if (null == pushRegidService) {
            return regids;
        }

        try {
            regids = pushRegidService.queryRegids(FrameUtil.newHashMap("user_ids", user_ids));
        }catch (Exception e) {
            // Don't worries.
            logger.error("push message occur exception:", e);
        }

        return regids;
    }

    private static JPushClient getClinent() throws Exception {
        if (null == jPushClient) {
            synchronized(JpushUtil.class){
                if (null == jPushClient) {
                    SysParamModel sysParam = SysParamUtil.getSysParamModel(Constant.SysParamKeyEnum.MFQ_APP_JPUSH_CONFIG);
                    ClientConfig clientConfig = ClientConfig.getInstance();
                    JpushConfiguration jpushConfig = JSON.parseObject(sysParam.getParam_value(), JpushConfiguration.class);
                    clientConfig.setMaxRetryTimes(jpushConfig.getMaxRetryTimes());
                    clientConfig.setApnsProduction(jpushConfig.isProduction());
                    clientConfig.setConnectionTimeout(jpushConfig.getConnTimeout());
                    clientConfig.setSSLVersion(jpushConfig.getSslVersion());
                    jPushClient = new JPushClient(jpushConfig.getMasterSecret(), jpushConfig.getAppKey(), null, clientConfig);
                }
            }
        }
        return jPushClient;
    }

    private static IPushRecordService getPushRecordService(){
        if(null == pushRecordService){
            synchronized(JpushUtil.class){
                if(null == pushRecordService){
                    pushRecordService = ServiceHolder.getLocalService(IPushRecordService.class, "pushRecordService");
                }
            }
        }

        return pushRecordService;
    }
}
